const axios = require('axios');
const xlsx = require('xlsx');

const url = 'http://localhost:9527/api-cemc/items/pagedstat?hostid=1020500&groupid=-1&name=&applicationName=&key=&delay=&history=&trends=&type=-1&valueType=-1&state=-1&status=-1&hadTrigger=-1&hadTemplate=-1&subApplicationNames=&subTypes=&subValueTypes=&subStates=&subHadTemplates=&subHadTriggers=&subHasDiscoveries=&subHistories=&subTrends=&subDelays=&sort=name%2Casc&page=0&size=2000&checkValue=false&action=&totalCount=0';

// 请求头配置
const headers = {
  'Accept': 'application/json, text/plain, */*',
  'Accept-Language': 'zh-CN,zh;q=0.9',
  'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJyb290Iiwic2Vzc2lvbmlkIjoiNjkwNGM0ZjUxNjZjNTUwNDBjN2U1NzYwNDNhZTU0NjkiLCJleHAiOjE3MzM5OTg0NDAsImlhdCI6MTczMzk5NDg0MH0.ciX0He9N6D4sXsI7YD56ajjfPC849oN2EgYmX1GJBw5vkzIb5OFYXzPblJIfbV-6-_sfs4iNKqnjBiGvueZHcg',
  'Connection': 'keep-alive',
  'Cookie': 'authorized-token={%22accessToken%22:%22eyJhbGciOiJIUzUxMiJ9.admin%22%2C%22expires%22:1919520000000%2C%22refreshToken%22:%22eyJhbGciOiJIUzUxMiJ9.adminRefresh%22}; multiple-tabs=true; sidebarStatus=0',
  'Referer': 'http://localhost:9527/cemc/maintainmonitoring/itemlist?filterSet=1&hostid=1004776',
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
  'dnt': '1'
};

axios.get(url, { headers })
  .then(({data}) => {
    // 检查返回的数据是否存在并且是有效数组
    if (data.result && Array.isArray(data.result.itemData.content)) {
      const jsonData = data.result.itemData.content;

      // 按 appName 分类数据
      const categorizedData = {};

      jsonData.forEach(item => {
        let appname = '其他';
        if (item.belongApplicationList && item.belongApplicationList[0]) {
          appname = item.belongApplicationList[0].name;
        }
        if (!categorizedData[appname]) {
          categorizedData[appname] = []; // 如果该类别不存在，先初始化为空数组
        }
        categorizedData[appname].push(item.name);
      });

      // 创建数据数组，按照分类显示
      const outputData = [];
      Object.keys(categorizedData).forEach(appname => {
        const names = categorizedData[appname];
        // 第一列为分类名称，第二列为具体内容
        names.forEach((name, index) => {
          if (index === 0) {
            outputData.push([appname, name]);
          } else {
            outputData.push(['', name]);
          }
        });
      });

      // 将数据转换为工作表
      const ws = xlsx.utils.aoa_to_sheet(outputData);

      // 创建工作簿并添加工作表
      const wb = xlsx.utils.book_new();
      xlsx.utils.book_append_sheet(wb, ws, '分类数据');

      // 写入 Excel 文件
      xlsx.writeFile(wb, 'D:/categorized_items.xlsx');
      console.log('数据已成功写入categorized_items.xlsx文件');
    } else {
      console.error('返回的数据结构不符合预期，无法处理内容');
      console.log(response.data); // 输出返回的数据以便调试
    }
  })
  .catch(error => {
    console.error('请求失败:', error);
  });
